import time
from socket import *
hostname =gethostname()# 获取主机名
ServerName=gethostbyname(hostname)# 获取IP地址
serverPort = 12000#端口号
clientSocket = socket(AF_INET, SOCK_DGRAM)#创建套接字
clientSocket.settimeout(1) # 设置超时时间为 1s
for i in range(0, 10):
    oldTime = time.time()
    sendTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(oldTime))#发送时间
    message = ('package %d,client_local_time:%s' % (i + 1, sendTime)).encode()#数据中包含序号和发送时间
    try:
        
        clientSocket.sendto(message, (ServerName, serverPort))# 发送数据
        modifiedMessage, serverAddress = clientSocket.recvfrom(1024)# 接收数据
        rtt = time.time() - oldTime# 计算往返时间
        print('报文 %d 收到来自 %s 的应答: %s, 往返时延(RTT) = %fs' % (i+1, ServerName,modifiedMessage.decode("utf-8"), rtt))#输出往返时间
    except Exception as e:
        print('报文 %d: 的请求超时' % (i+1)) # 处理异常